<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="10">
          <el-input
            placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="5">
            <el-button type="primary" @click="addUser=true">添加用戶</el-button>
        </el-col>
      </el-row>
      <el-table :data="usersList" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
            <template slot-scope="scope">
                <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)"></el-switch>
            </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
            <template slot-scope="scope">
                <el-tooltip  effect="dark" content="修改角色" placement="top" :enterable="false">
                    <el-button type="primary" @click="editUser(scope.row.id)" icon="el-icon-edit" size="mini"></el-button>
                </el-tooltip>
                <el-tooltip  effect="dark"  content="删除角色" placement="top" :enterable="false">
                    <el-button type="danger" icon="el-icon-delete" @click="removeUserById(scope.row.id)" size="mini"></el-button>
                </el-tooltip>
                <el-tooltip  effect="dark" content="分配角色" placement="top" :enterable="false">
                    <el-button @click="handleChangeUser(scope.row)" type="warning" icon="el-icon-setting" size="mini"></el-button>
                </el-tooltip>
            </template>
        </el-table-column>
      </el-table>
       
      <!-- 分页部分 -->
      <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.pagenum"
      :page-sizes="[1, 3, 5, 10]"
      :page-size="queryInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    </el-card>
    <!-- 添加用戶 -->
    <el-dialog @close="handleDialogClose" title="添加用户" :visible.sync="addUser" width="50%">
      <el-form :model="addForm" :rules="addRules" ref="addFormRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addUser = false">取 消</el-button>
        <el-button type="primary" @click="handleAddUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户 -->
    <el-dialog @close="editDialogClose" title="修改用户" :visible.sync="editDialogVisible" width="50%">
      <el-form ref="editFromRef" :model="editFrom" label-width="80px" :rules="editFromRules">
        <el-form-item label="用户名">
          <el-input v-model="editFrom.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editFrom.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editFrom.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCheck">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 点击分配角色弹框询问 -->
    <el-dialog title="分配角色" :visible.sync="setRoleDialogVisible" width="50%"  @close="setHandleClose">
      <el-form :model="userInfo" status-icon ref="" label-width="100px">
        <el-form-item label="当前的用户:">
          <el-input v-model="userInfo.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="当前的角色:">
          <el-input  v-model="userInfo.role_name" disabled></el-input>
        </el-form-item>
      </el-form>
      <span style="margin-left:27px">用户权限:&nbsp;</span>
      <el-select  style="margin-left:8px" v-model="selectRoleId" placeholder="请选择">
          <el-option  v-for="item in rolesList" :key="item.id" :label="item.roleName" :value="item.id">
          </el-option>
      </el-select>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>

export default {

  data() {
    var checkMobile= (rule,value,callback)=>{
      const regMobile = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/
      if (regMobile.test(value)) {
        return callback()
      }
      callback(new Error("请输入合法的手机号"))
    }
    return {
        queryInfo:{
            query:'',
            pagenum:1,
            pagesize:5
        },
        usersList:[],
        total:0,
        addUser:false,
        addForm:{
          username:'',
          password:'',
          email:'',
          mobile:''
        },
        addRules:{
          username:[
            {required:true,message:'请输入用户名',trigger:'blur'},
            {min:3,max:5,message:'用户名长度是3~5个字符之间',trigger:'blur'}
          ],
          password:[
            {required:true,message:'请输入密码',trigger:'blur'},
            {min:6,max:15,message:'密码长度是3~5个字符之间',trigger:'blur'}
          ],
          email:[
          {required:true,message:'请输入邮箱',trigger:'blur'},
            {
              type: 'string',
              message: '邮箱格式不正确',
              trigger: 'blur',
              transform(value) {
                if (!/^\w+((-\w+)|(\.\w+))*@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/.test(value)) {
                  return true
                } else {
                }
              }
      },
          ],
          mobile:[
          {required:true,message:'请输入手机号',trigger:'blur'},
          {validator:checkMobile,trigger: 'blur',}
          ]
        },
        // 修改用户对话框的显示与隐藏
        editDialogVisible:false,
        editFrom:{},
        // 修改表单的验证规则
        editFromRules:{
          email:[
          {required:true,message:'请输入邮箱',trigger:'blur'},
            {
              type: 'string',
              message: '邮箱格式不正确',
              trigger: 'blur',
              transform(value) {
                if (!/^\w+((-\w+)|(\.\w+))*@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/.test(value)) {
                  return true
                } else {
                }
              }
      },
          ],
          mobile:[
          {required:true,message:'请输入手机号',trigger:'blur'},
          {validator:checkMobile,trigger: 'blur',}
          ]
        },
        setRoleDialogVisible:false,
        //单行的全部数据
        userInfo:{},
        rolesList:[],
        selectRoleId:''
    };
  },
  created(){
    this.getUserList()
  },
  mounted() {},

  methods: {
    async getUserList(){
       const {data:res} = await this.$http.get('users',{params:this.queryInfo})
       if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
       }
       this.usersList = res.data.users
       this.total = res.data.total
    },
    handleSizeChange(e){
        this.queryInfo.pagesize = e
        this.getUserList()
    },
    handleCurrentChange(e){
        this.queryInfo.pagenum = e
        this.getUserList()
    },
    async userStateChange(e){
      const {data:res} = await this.$http.put(`users/${e.id}/state/${e.mg_state}`)
      if (res.meta.status !== 200) {
        e.mg_state = !e.mg_state
        return this.$message.error(res.meta.msg)
       }
       this.$message.success('用户状态修改成功')

    },
    //点击关闭对话框清除输入框内容
    handleDialogClose(){
      this.$refs.addFormRef.resetFields()
    },
    //点击添加用户
    handleAddUser(){
      this.$refs.addFormRef.validate(async valid=>{
        if (!valid) return 
        const {data:res} = await this.$http.post('users',this.addForm)
        console.log(res);
        
        if (res.meta.status!==201) {
          this.$message.error(res.meta.msg)
        }
        this.$message.success(res.meta.msg)
        this.addUser = false
        this.getUserList()
      })
    },
    async editUser(id){
      const {data:res} = await this.$http.get('users/' + id)
      if (res.meta.status!==200) {
        return this.$message.error(res.meta.msg)
      }
      this.editFrom = res.data

      this.editDialogVisible = true
    },
    editDialogClose(){
      this.$refs.editFromRef.resetFields()
    },
    //点击确定之后对输入内容进行校验
    editCheck(){
      this.$refs.editFromRef.validate(async valid=>{
        if(!valid) return
        const {data:res} = await this.$http.put('users/'+ this.editFrom.id,{email:this.editFrom.email,mobile:this.editFrom.mobile})
        if (res.meta.status!==200) {
        return this.$message.error(res.meta.msg)
      }
       //关闭对话框
      this.editDialogVisible=false
      //刷新数据
      this.getUserList()
      //提示成功
      this.$message.success(res.meta.msg)
      })
      
    },
    //删除角色
    async removeUserById(id){
      await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
         this.$http.delete('users/'+id)
         
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
        this.getUserList()
    },
    //分配用户角色
    async handleChangeUser(userInfo){
      this.userInfo = userInfo
      // 获取角色列表
      const {data:res} = await this.$http.get('roles')
      this.rolesList = res.data
      this.setRoleDialogVisible = true
    },
    // 点击按钮分配角色
    async saveRoleInfo(){
      if (!this.selectRoleId) {
        return this.$message.error('请选择要分配的角色')
      }else{
      const {data:res}  = await this.$http.put(`users/${this.userInfo.id}/role`,{rid:this.selectRoleId})
      this.$message.success(res.meta.msg)
      this.getUserList()
      this.setRoleDialogVisible = false
      }
    },
    setHandleClose(){
      this.selectRoleId = ''
      this.userInfo = {}
    },
  }
};
</script>

<style lang="less" scoped></style>
